<template>
  <div class="notice">
    <div class="notice-bar" :style="config.bg_color? ' background:'+config.bg_color: ''">
      <div class="notice-bar-icon"></div>
      <div class="marquee-wrap" @click="jump">
        <div class="scroll">
          <p
            class="marquee"
            :style="config.color ? 'color:'+ config.color : ''"
          >{{ getContent() }}</p>
          <p class="copy" :style="config.color ? 'color:'+ config.color : ''"></p>
        </div>
        <p class="getWidth">{{ getContent() }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['value'],
  data() {
    return {
      config: this.value ? this.value : {},
      nowTime: null
    }
  },
  watch: {
    value(newVal) {
      this.config = newVal
    }
  },
  mounted(){
    console.log('mounted: move')
    this.move()
  },
  updated() {
    this.move()
  },
  beforeDestroy() {
    clearInterval(this.nowTime)
    this.nowTime = null
  },
  methods: {
    jump() {
      console.log('jump')
      this.$router.push(this.config.link)
    },
    move() {
      let scroll = document.querySelector('.scroll')
      if (this.nowTime != null) {
        clearInterval(this.nowTime)
        document.querySelector('.copy').innerText = ''
        scroll.style.transform = 'translateX(0px)'
      }
      let maxWidth = document.querySelector('.marquee-wrap').clientWidth
      let width = document.querySelector('.getWidth').scrollWidth
      if (width <= maxWidth/2) return
      let distance = 0
      document.querySelector('.copy').innerText = this.getContent()
      this.nowTime = setInterval(() => {
        distance -= 1
        if (-distance >= maxWidth) {
          distance = 0
        }
        scroll.style.transform = 'translateX(' + distance + 'px)'
      }, 30)
    },
    getContent(){
      return this.config.content || '请填写内容，如果过长，将会在手机上滚动显示'
    }
  }
}
</script>

<style lang="less">
.notice {
  width: 100%;
  overflow: hidden;
  position: relative;
  .notice-bar {
    width: 100%;
    height: 40px;
    display: flex;
    justify-items: center;
    align-items: center;
    .notice-bar-icon {
      width: 16px;
      height: 16px;
      background-image: url('../assets/img/laba.png');
      background-size: 16px 16px;
      margin: 10px;
    }

    .marquee-wrap {
      width: 100%;
      overflow: hidden;
      position: relative;
      .scroll {
        display: flex;
        p {
          word-break: keep-all; // 不换行
          white-space: nowrap;
          /* 设置前后间隔 */
          &.marquee {
            margin-right: 36px;
          }
        }
      }
      /* 仅为了获取宽度，故隐藏掉 */
      .getWidth {
        word-break: keep-all; // 不换行
        white-space: nowrap;
        position: absolute;
        opacity: 0;
        top: 0;
      }
    }
  }
}
</style>
